import logging
import formencode

import os, sys, codecs
from subprocess import *
import re
from urllib import unquote

from wiki.lib.base import *
import wikianalysis

log = logging.getLogger(__name__)

MAIN_PAGE_ARTICLES = 10
SEARCH_RESULT_LIMIT = 5000
CLASSIFY_LIMIT = 4000
CACHE_TIME = 5
HIGHLIGHT = True

SEARCHPAGE = '<p>Please enter a search term.</p>'

class HomeController(BaseController):
    
    def index(self):
        # check session position
        start = 0
        try: start = session['random_pos']
        except: pass
        
        # grab the links
        if start + MAIN_PAGE_ARTICLES > len(g.random_articles): start = 0
        links = g.random_articles[start:start+MAIN_PAGE_ARTICLES]        
        
        # save the new position
        session['random_pos'] = start + MAIN_PAGE_ARTICLES
        session.save()
        
        c.body = '<ul>\n'+'\n'.join(links)+'\n</ul>'
        return render('/wiki.mako')  ###, cache_expires=CACHE_TIME)
    
    
    def search(self):
        etag_cache('search')
        
        # get the term
        term = ''
        try: term = request.params['term'].lower()
        except: pass
        if term == '': 
            c.body = SEARCHPAGE
            return render('/search.mako', cache_expires=CACHE_TIME)
            
        # make sure we are dealing with the right type of unicode
        searchterm = term
        if not isinstance(searchterm, str):
            searchterm = searchterm.encode('utf-8')
        
        # init the cache
        search_cache = cache.get_cache('search')
        
        # search cache function
        def perform_search():
            links = []
            count = 0
            lowered = g.search_lower
            titles = g.search_links
            
            for i in xrange(len(titles)):
                if lowered[i].find(term) != -1:
                    links.append(titles[i])
                    count += 1
                    if count == SEARCH_RESULT_LIMIT: break
            
            if count == 0: return 'No articles found for "%s".' % term.replace('<','&lt;').replace('>','&gt;')
            
            # return links of matches     
            return '<ul>\n'+'\n'.join(links)+'\n</ul>'
        
        # render
        c.body = search_cache.get_value(key=searchterm, createfunc=perform_search, expiretime=CACHE_TIME)
        c.term = term
        return render('/search.mako', cache_expires=CACHE_TIME)
    
    def article(self):
        etag_cache('article')      
        title = self.getTitle()
        name = title.replace('_', ' ')
        
        # make sure we are dealing with the right type of unicode
        key = name
        if not isinstance(name, str):
            key = name.encode('utf-8')
        page_id = g.article_dict.get(key)
        if page_id == None: redirect_to('/')
        
        c.title = title
        c.name = name
        c.page_id = page_id
        return render('/article.mako', cache_expires=CACHE_TIME)

    """ helper functions """
    def getTitle(self):
        url = h.url_for()
        title = url[url.rfind('/')+1:]
        title = unquote(title).decode('utf-8')
        return title



